package com.jfeat.am.module.wegou.services.patch.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.jfeat.am.common.exception.BusinessException;
import com.jfeat.am.module.wegou.exception.WegouBizException;
import com.jfeat.am.module.wegou.services.crud.service.ProductStoreService;
import com.jfeat.am.module.wegou.services.patch.ProductTypePatchService;
import com.jfeat.am.module.wegou.services.persistence.dao.ProductMapper;
import com.jfeat.am.module.wegou.services.persistence.dao.ProductTypeMapper;
import com.jfeat.am.module.wegou.services.persistence.model.Product;
import com.jfeat.am.module.wegou.services.persistence.model.ProductType;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class ProductTypePatchServiceImpl implements ProductTypePatchService {
    @Resource
    ProductTypeMapper productTypeMapper;
    @Resource
    ProductMapper productMapper;
    @Resource
    ProductStoreService productStoreService;

    @Override
    public boolean hasChildren(Long id) {
        ProductType productType = productTypeMapper.selectById(id);
        List<ProductType> productTypes = productType.selectList(new EntityWrapper<ProductType>().eq(ProductType.PID, id));
        return productTypes.size() > 0;
    }

    @Override
    public boolean refBySomeProducts(Long id) {
        List<Product> products = productMapper.selectList(new EntityWrapper<Product>().eq(Product.PRODUCT_TYPE_ID, id));
        return products.size() > 0;
    }

    @Override
    public boolean isProductTypeNameDuplicated(Long stireId, ProductType productType, boolean excluded) {
        List<ProductType> productTypes = productTypeMapper.selectList(
                new EntityWrapper<ProductType>().eq(ProductType.STORE_ID, stireId)
        );
        for (ProductType pt : productTypes) {
            if (excluded && pt.getId().equals(productType.getId())) {
                continue;
            }
            if (pt.getTypeName().equals(productType.getTypeName())) {
                throw new BusinessException(WegouBizException.DULPLICATED_PRODUCT_TYPE_NAME.getCode(),
                        String.format(WegouBizException.DULPLICATED_PRODUCT_TYPE_NAME.getMessage(), pt.getTypeName()));
            }
            if (pt.getZhTypeName().equals(productType.getZhTypeName())) {
                throw new BusinessException(WegouBizException.DULPLICATED_PRODUCT_TYPE_NAME.getCode(),
                        String.format(WegouBizException.DULPLICATED_PRODUCT_TYPE_NAME.getMessage(), pt.getZhTypeName()));
            }
        }
        return false;
    }

}
